package com.andy.service;

import java.util.Iterator;
import java.util.Set;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.andy.dao.IExamUserDAO;
import com.andy.entity.ExamRole;
import com.andy.entity.ExamUser;
import com.andy.vo.ExamUserVO;

@Service
@Transactional
public class ExamUserService implements IExamUserService {
	
	@Autowired
	private IExamUserDAO examUserDAO;
	
	@Override
	public ExamUserVO getUserById(String userId) {
		ExamUser user = examUserDAO.get(userId);
		if (user != null) {
			ExamUserVO resultVO = new ExamUserVO();
			BeanUtils.copyProperties(user, resultVO);
			Set<ExamRole> roleSet = user.getExamRoles();
			if (roleSet != null && roleSet.size() > 0) {
				Iterator<ExamRole> it = roleSet.iterator();
				if (it.hasNext()) {
					ExamRole role = it.next();
					resultVO.setUserRole(role.getRoleId());
				}
			}
			return resultVO;
		}
		return null;
	}

	@Override
	public void updateUserLoginFailCount(ExamUserVO resultVO) {
		ExamUser user = examUserDAO.get(resultVO.getUserId());
		if (user != null) {
			user.setLoginFailCount(resultVO.getLoginFailCount());
			examUserDAO.update(user);
			examUserDAO.flush();
		}
	}

	@Override
	public void updateUserLastLockTime(ExamUserVO resultVO) {
		ExamUser user = examUserDAO.get(resultVO.getUserId());
		if (user != null) {
			user.setLastLockTime(resultVO.getLastLockTime());
			examUserDAO.update(user);
			examUserDAO.flush();
		}
	}

}
